/** @format */

const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(cors());
// 天干和地支数组
const TIANGAN = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const DIZHI = [
  '子',
  '丑',
  '寅',
  '卯',
  '辰',
  '巳',
  '午',
  '未',
  '申',
  '酉',
  '戌',
  '亥',
];

// 判断是否为公历闰年
function isLeapYear(year) {
  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) return true;
  if (year % 3200 === 0 && year % 172800 !== 0) return true;
  return false;
}

// 获取某年的天数
function getTotalDaysInYear(year) {
  return isLeapYear(year) ? 366 : 365;
}

// 获取某个月的天数（公历）
function getDaysInMonth(year, month) {
  const daysPerMonth = [
    31,
    isLeapYear(year) ? 29 : 28,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31,
  ];
  return daysPerMonth[month];
}

// 根据基准日期计算干支
function calculateGanzhi(baseGanzhi, offset) {
  const tianganIndex = (TIANGAN.indexOf(baseGanzhi[0]) + offset) % 10;
  const dizhiIndex = (DIZHI.indexOf(baseGanzhi[1]) + offset) % 12;
  return `${TIANGAN[tianganIndex]}${DIZHI[dizhiIndex]}`;
}

// 生成某年的干支表，按月份分组
function generateGanzhiYear(year) {
  const result = Array.from({ length: 12 }, () => []);
  const baseDate = new Date(1900, 0, 31); // 基准日：1900-01-31（甲子日）
  const baseGanzhi = '甲子';

  // 遍历整年每一天
  const totalDaysBeforeYear = Math.floor(
    (new Date(year, 0, 1) - baseDate) / (1000 * 60 * 60 * 24)
  );
  let currentGanzhi = calculateGanzhi(baseGanzhi, totalDaysBeforeYear);

  for (let month = 0; month < 12; month++) {
    const daysInMonth = getDaysInMonth(year, month);
    for (let day = 1; day <= daysInMonth; day++) {
      const date = `${year}-${String(month + 1).padStart(2, '0')}-${String(
        day
      ).padStart(2, '0')}`;
      result[month].push({
        date,
        ganzhi: currentGanzhi,
      });
      currentGanzhi = calculateGanzhi(currentGanzhi, 1); // 每天推进一天
    }
  }

  return result;
}

// Express 路由
app.use(express.json());

// 接收年份并生成干支表
app.post('/generate-ganzhi', (req, res) => {
  const { year } = req.body;
  console.log(year, 'year');
  // 验证输入年份
  if (!year || isNaN(year) || year < 0) {
    return res.status(400).json({ error: '请提供一个有效的年份（正整数）' });
  }

  // 生成干支数据
  try {
    const ganzhiData = generateGanzhiYear(parseInt(year, 10));
    res.json(ganzhiData);
  } catch (err) {
    res.status(500).json({ error: '内部服务器错误', details: err.message });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`干支纪年接口已启动：http://localhost:${port}`);
});
